const state = {
  // 缓存的海报图片
  cachedPoster: uni.getStorageSync('cachedPoster') || '',
  // 缓存的二维码图片
  cachedQrCode: uni.getStorageSync('cachedQrCode') || '',
  // 海报生成状态
  isGenerating: false,
  // 海报生成时间戳
  lastGeneratedTime: 0
}

const mutations = {
  // 设置缓存的海报图片
  SET_CACHED_POSTER(state, posterUrl) {
    state.cachedPoster = posterUrl
    // 持久化存储
    if (posterUrl) {
      uni.setStorageSync('cachedPoster', posterUrl)
    } else {
      uni.removeStorageSync('cachedPoster')
    }
  },
  
  // 设置缓存的二维码图片
  SET_CACHED_QRCODE(state, qrCodeUrl) {
    state.cachedQrCode = qrCodeUrl
    // 持久化存储
    if (qrCodeUrl) {
      uni.setStorageSync('cachedQrCode', qrCodeUrl)
    } else {
      uni.removeStorageSync('cachedQrCode')
    }
  },
  
  // 设置海报生成状态
  SET_GENERATING_STATUS(state, status) {
    state.isGenerating = status
  },
  
  // 设置最后生成时间
  SET_LAST_GENERATED_TIME(state, timestamp) {
    state.lastGeneratedTime = timestamp
  },
  
  // 清除所有海报缓存
  CLEAR_POSTER_CACHE(state) {
    state.cachedPoster = ''
    state.cachedQrCode = ''
    state.isGenerating = false
    state.lastGeneratedTime = 0
    // 清除持久化存储
    uni.removeStorageSync('cachedPoster')
    uni.removeStorageSync('cachedQrCode')
  }
}

const actions = {
  // 设置缓存的海报图片
  setCachedPoster({ commit }, posterUrl) {
    commit('SET_CACHED_POSTER', posterUrl)
  },
  
  // 设置缓存的二维码图片
  setCachedQrCode({ commit }, qrCodeUrl) {
    commit('SET_CACHED_QRCODE', qrCodeUrl)
  },
  
  // 设置生成状态
  setGeneratingStatus({ commit }, status) {
    commit('SET_GENERATING_STATUS', status)
  },
  
  // 设置最后生成时间
  setLastGeneratedTime({ commit }, timestamp) {
    commit('SET_LAST_GENERATED_TIME', timestamp)
  },
  
  // 清除海报缓存
  clearPosterCache({ commit }) {
    commit('CLEAR_POSTER_CACHE')
  }
}

const getters = {
  // 获取是否有缓存的海报
  hasCachedPoster: state => !!state.cachedPoster,
  
  // 获取是否有缓存的二维码
  hasCachedQrCode: state => !!state.cachedQrCode,
  
  // 获取缓存是否有效（30天有效期）
  isCacheValid: state => {
    if (!state.lastGeneratedTime) return false
    const now = Date.now()
    const cacheExpireTime = 30 * 24 * 60 * 60 * 1000 // 30天
    return (now - state.lastGeneratedTime) < cacheExpireTime
  }
}

export default {
  namespaced: true,
  state,
  mutations,
  actions,
  getters
} 